import PubSub from 'pubsub-js';
import config from '../../../utils/config';
import request from '../../../utils/request';

Page({
    data:{
        day:'',
        month: '',
        recommendSongList:[],
        index: 0  //音乐的下标
    },
    onLoad: function(options){
        // 判断用户是否登录
        const userInfo = wx.getStorageSync('userInfo');
        if(!userInfo){
            wx.showToast({
                title: '请先登录',
                icon: 'none',
                mask: true,
                success: (res)=>{
                    // 跳转至登录页面
                    wx.reLaunch({
                        url: '/pages/login/login'
                    });
                }
            });

        }

        // 获取日期
        const month = new Date().getMonth() + 1;
        this.setData({
            day: new Date().getDate(),
            month: month > 10 ? month : '0' + month
        });

        this.getRecommendSongs();

        //订阅来自song-play页面发布的消息
        PubSub.subscribe('switchType',(msg, data) => {
            console.log('msg, data:',msg, data);
            let { recommendSongList,index } = this.data;
            if(data == 'pre'){
                // 上一首
                index -= 1;
                if(index < 0)index = recommendSongList.length - 1;
            }else{
                // 下一首
                index += 1;
                if((index + 1) > recommendSongList.length)index = 0;
            }
            // 更新下标
            this.setData({
                index
            });
            // 回传给song-play页面
            const musicId = recommendSongList[index].id;
            PubSub.publish('musicId',musicId);
        });
    },
    // 获取每日推荐数据
    async getRecommendSongs(){
        const res = await request(config.recommendSong);
        this.setData({
            recommendSongList: res.recommend
        });
    },
    // 跳转至音乐播放页面
    toSongPlay(e){
        const { music,index } = e.currentTarget.dataset;
        this.setData({
            index
        });
        // 路由跳转传参:支持query参数
        // 原生小程序路由传参，对参数长度有限制，如果参数长度过长会自动截取
        wx.navigateTo({
           url: '/songPackage/pages/song-play/song-play?musicId=' + music.id
        });
    }
})